package com.amita.ez.base;

import com.amita.ez.entity.SysUser;
import com.amita.ez.service.IUserInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component
public class CorsFilter implements Filter {

    @Autowired
    IUserInfoService userInfoService;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {


        HttpServletResponse res = (HttpServletResponse) response;
        res.addHeader("Access-Control-Allow-Credentials", "true");
        res.addHeader("Access-Control-Allow-Origin", "*");
        res.addHeader("Access-Control-Allow-Methods", "GET,POST,DELETE,PUT");
        res.addHeader("Access-Control-Allow-Headers", "Content-Type,X-CAF-Authorization-Token,sessionToken,X-TOKEN,token,Authorization");
        if (((HttpServletRequest) request).getMethod().equals("OPTIONS")) {
            response.getWriter().println("ok");
            return;
        }
        HttpServletRequest req = (HttpServletRequest) request;

        String url = req.getRequestURL().toString();
//        System.out.println(url);
        if(url.endsWith("/api/login") ||!url.contains("/api/")){
            chain.doFilter(request, response);
        }else{
            String xtoken = req.getHeader("Authorization");
            if(xtoken == null){
                res.sendError(401, "no login");
                return;
            }
            SysUser userInfo = userInfoService.getByToken(xtoken);
            if(userInfo!= null){
                chain.doFilter(request, response);
            }else{
//                HttpServletResponse res = (HttpServletResponse) response;
//                res.addHeader("Content-Type", " application/json");
                res.sendError(401, "no login");
                return;
            }

        }

//        chain.doFilter(request, response);
    }

//    @Override
//    public void destroy() {
//
//    }
}
